<template>
    <div>
        <div v-show="activeStatu">
            <el-card class="box">
                <!-- 搜索筛选名称或标题 -->
                <div style="padding: 10px">
                    <div class="flex">
                        <div style="width: 220px">分类标题</div>
                        <div class="time_top">创建时间</div>
                    </div>
                    <div class="flexBox">
                        <div> 
                            <el-input v-model.trim="inputed" @input="filters" placeholder="输入内容" style="width: 220px">
                                <template #prefix>
                                    <el-icon class="el-input__icon">
                                        <search />
                                    </el-icon>
                                </template>
                            </el-input>
                        </div>
                        <div style="margin-left: 20px;">
                            <el-date-picker style="width: 220px" @change="data_filters" v-model="time" type="daterange"
                                range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" />
                        </div>
                    </div>
                    <div style="display: flex;">
                        <div><el-button type="primary" @click="add" class="add_class">
                                新增</el-button>
                        </div>
                        <el-button type="danger" class="delelist" @click="deleList">批量删除</el-button>
                    </div>
                    <!-- table表格数据展示 -->
                    <div> 
                        <el-table :data="activeList.slice((currentPage - 1) * pageSize, currentPage * pageSize)"
                            style="margin-top: 10px;width: 100%;" :cell-style="{ 'text-align': 'center' }" lazy="true"
                            height="285" v-el-table-infinite-scroll="handleTableScroll"
                            :header-cell-style="{ 'text-align': 'center' }" @selection-change="handleSelectionChange">
                            <el-table-column type="selection" fixed="left" />
                            <el-table-column prop="id" label="序号" fixed="left" />
                            <el-table-column prop="title" label="标题名称" show-overflow-tooltip />
                            <el-table-column prop="createtime" label="创建时间" />
                            <el-table-column label="操作" width="250" fixed="right">
                                <template #default="scope">
                                    <div class="handle">
                                        <div @click="edit(scope.row)"
                                            style="color: rgba(64, 158, 255, 1); cursor: pointer;">编辑</div>
                                        <div style="width: 10px;"></div>
                                        <div @click="deletes(scope.row)" style="color: red; cursor: pointer;">删除</div>
                                    </div>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                    <div class="paging">
                        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                            :page-sizes="[5, 10, 20, 50]" :small="small" :disabled="disabled" background
                            layout="total, sizes, prev, pager, next, jumper" :total="activeList.length" />
                    </div>
                    <!-- 删除弹窗 -->
                    <el-dialog title="删除" v-model="centerDialogVisible" width="30%" center>
                        <div style="font-size: 16px; padding-bottom: 20px">确认删除该门店类型吗?</div>
                        <div style="display: flex; justify-content: end">
                            <el-button @click="centerDialogVisible = false">取 消</el-button>
                            <el-button type="primary" @click="deleteid">确 定</el-button>
                        </div>
                    </el-dialog>
                </div>
                <el-dialog v-model="shows" title="是否要删除" center width="20vw">
                    <el-button @click="shows = false">取 消</el-button>
                    <el-button type="primary" @click="oks">确 定</el-button>
                </el-dialog>
                <!-- 批量删除 -->
                <el-dialog title="批量删除" v-model="centerDialogVisiblet" width="30%" center>
                    <div style="font-size: 16px">确认删除这批数据吗?</div>
                    <span slot="footer" style="display: flex; justify-content: space-between" class="dialog-footer">
                        <div></div>
                        <div>
                            <el-button @click="centerDialogVisiblet = false">取 消</el-button>
                            <el-button type="primary" @click="deleteid_t">确 定</el-button>
                        </div>
                    </span>
                </el-dialog>
            </el-card>
        </div>

        <!-- 第二块 -->
        <div v-show="activeStatud" style="padding: 10px">
            <el-card style="width: 96%;margin-left: 2%;margin-top: 1%;position: relative;height: 80vh;">
                <div style="padding: 10px">{{ addText }}</div>
                <div style="width: 100%;height: 1px; background-color: rgba(195, 195, 195, 1);"></div>
                <div style="margin-top: 50px;margin-left: 100px;">
                    <el-form ref="ruleFormRef" style="width:50%" :model="ruleForm" status-icon :rules="rules"
                        label-position="left" label-width="auto" class="demo-ruleForm">
                        <el-form-item label="分类名称" prop="synopsis" style="width: 50%;">
                            <el-select v-model="ruleForm.synopsis" placeholder="请选择" style="width: 240px">
                                <el-option v-for="item in options" :key="item.id" :label="item.title"
                                    :value="item.id" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="标题名称" prop="name" style="width: 90%">
                            <el-input 
                                v-model.trim="ruleForm.name" 
                                placeholder="请输入" 
                                style="width: 90%" 
                                @blur="checkNameDuplicate"
                            />
                            <div v-if="nameDuplicateError" style="color: red; font-size: 12px;">
                                该名称已存在，请重新输入
                            </div>
                        </el-form-item>
                        <el-form-item label="标题图片" prop="img" style="width: 90%">
                            <!-- 单图图片 -->
                            <el-upload list-type="picture-card" accept=".jpeg,.png,.jpg,.bmp,.gif"
                                :on-preview="handlePictureCardPreviewt" :on-remove="handleRemovet"
                                :file-list="fileListt" :before-upload="beforeAvatarUploadt">
                                <el-icon>
                                    <Plus />
                                </el-icon>
                            </el-upload>
                        </el-form-item>
                    </el-form>
                    <div class="dialog-footer" style="position: absolute;bottom: 20px;right: 40px;">
                        <el-button type="primary" @click="submitForm(ruleFormRef)">确认</el-button>
                        <el-button @click="closes(ruleFormRef)">取消</el-button>
                    </div>
                </div>
            </el-card>
        </div>
        <el-dialog v-model="dialogVisiblet">
            <img style="width: 90%; height: 90%" w-full :src="dialogImageUrlt" alt="Preview Image" />
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, nextTick } from 'vue';
import { group_list, lark_list, lark_add, lark_del } from '../../../api/group/index'
import { ElMessage, ElCard } from 'element-plus';
import { scenicUpload } from '../../../api/uploading/index';

const dialogImageUrlt = ref('')
const dialogVisiblet = ref(false)
const nameDuplicateError = ref(false) // 名称重复错误提示
const originalName = ref('') // 保存编辑时的原始名称

// 图片数组
const fileListt = ref([]);
// 图片移除
const handleRemovet = (file, fileListt) => {
    console.log(file, fileListt);
    if (fileListt.length < 1) {
        ruleForm.img = ''
    }
};

// 图片上传回调事件
const beforeAvatarUploadt = (file) => {
    const fileName = file.name
    const fileType = fileName.substring(fileName.lastIndexOf('.'))
    // jpeg,.png,.jpg,.bmp,.gif
    if (
        fileType === '.jpg' ||
        fileType === '.png' ||
        fileType === '.jpeg' ||
        fileType === '.bmp' ||
        fileType === '.gif'
    ) {
    } else {
        ElMessage.error('不是,jpeg,.png,.jpg,.bmp,.gif文件,请上传正确的图片类型')
        return false
    }
    console.log(file);
    // 压缩图片
    compressImage(file).then(compressedBlob => {
        const formData = new FormData();
        formData.append('file', compressedBlob, file.name);
        if (file.size / 1024 / 1024 > 2) {
            console.log(file.size / 1024 / 1024);
            ElMessage.error('图片不能大于2MB!')
            return false
        } else {
            console.log(formData);
            scenicUpload(formData).then(res => {
                console.log(res);
                fileListt.value = [{
                    name: 'plant-1.png',
                    url: testName + res.data.url,
                }]
                ruleForm.img = res.data.url
            })
        }
    });
    return false; // 阻止默认上传行为
}

// 压缩图片方法
const compressImage = (file) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    return new Promise((resolve) => {
        reader.onload = e => {
            const img = new Image();
            img.src = e.target.result;
            img.onload = () => {
                const canvas = document.createElement('canvas');
                const ctx = canvas.getContext('2d');
                const { width, height } = img;
                canvas.width = width;
                canvas.height = height;
                ctx.drawImage(img, 0, 0, width, height);
                // 可以在这里调整压缩质量和尺寸
                const quality = 0.7; // 压缩质量
                const newImageData = canvas.toDataURL('image/jpeg', quality);
                const resizedBlob = dataURLtoBlob(newImageData);
                console.log(ctx);
                resolve(resizedBlob);
            };
        };
    });
};

const dataURLtoBlob = (dataurl) => {
    const arr = dataurl.split(',');
    const mime = arr[0].match(/:(.*?);/)[1];
    const bstr = atob(arr[1]);
    let n = bstr.length;
    const u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], { type: mime });
};

const options = ref([])
const time = ref('')
// 创建数据变量
const activeList = ref([]);
const activeStatu = ref(true)
const activeStatud = ref(false)
const names = ref('导出');
import { inject } from 'vue'
const testFn = inject('testFn')
testFn()
const testName = inject('testName')
const dialogTableVisible = ref(false);
const statused = ref('1');
// 表格页码数
const inputed = ref('');
const pageSize = ref(5);
const currentPage = ref(1);
const copyList = ref([]);
const files = ref(false);

// 名称查重函数
const checkNameDuplicate = async () => {
    if (!ruleForm.name) return;
    
    // 如果是编辑状态且名称没有变化，则不检查
    if (statused.value === '2' && ruleForm.name === originalName.value) {
        nameDuplicateError.value = false;
        return;
    }
    
    // 检查本地数据中是否存在相同名称
    const isDuplicate = activeList.value.some(item => 
        item.title === ruleForm.name && 
        (statused.value === '1' || item.id !== ids.value) // 编辑时排除自身
    );
    
    if (isDuplicate) {
        nameDuplicateError.value = true;
        await nextTick();
        ruleFormRef.value.validateField('name');
    } else {
        nameDuplicateError.value = false;
    }
};

// 请求接口并开局渲染
let tokens = JSON.parse(localStorage.getItem('tokens'));
console.log(tokens);
render();

function render() {
    lark_list({
        token: tokens.token,
        uid: tokens.userinfo.id
    }, {
        userid: tokens.userinfo.id
    }).then((res) => {
        console.log(res);
        activeList.value = res.data;
        copyList.value = res.data;
    });
    group_list({
        token: tokens.token,
        uid: tokens.userinfo.id
    }, {
        userid: tokens.userinfo.id
    }).then((res) => {
        console.log(res);
        options.value = res.data
    });
}

// 点击新增
const addText = ref("")
function add() {
    activeStatu.value = false
    addText.value = '添加'
    activeStatud.value = true
    dialogTableVisible.value = true;
    statused.value = '1';
    disableds.value = true;
    ruleForm.name = '';
    ruleForm.start_time = '';
    ruleForm.end_time = '';
    ruleForm.details = '';
    ruleForm.img = '';
    ruleForm.synopsis = '';
    nameDuplicateError.value = false;
    originalName.value = '';
}

// 表单对象
const ruleForm = reactive({
    name: '',
    start_time: '',
    end_time: '',
    details: '',
    img: '',
    synopsis: '',
});
const ruleFormRef = ref('');
const rules = reactive({
    name: [
        {
            required: true,
            message: '请输入分类名称',
            trigger: 'blur',
        },
        {
            validator: (rule, value, callback) => {
                if (nameDuplicateError.value) {
                    callback(new Error('该名称已存在'));
                } else {
                    callback();
                }
            },
            trigger: 'blur'
        }
    ],
    start_time: [
        {
            required: true,
            message: '请选择开始时间',
            trigger: 'blur',
        },
    ],
    end_time: [
        {
            required: true,
            message: '请输入结束时间',
            trigger: 'blur',
        }, 
        { 
            validator: validateEmailDomain, 
            trigger: 'blur' 
        }
    ],
    details: [
        {
            required: true,
            message: '请输入活动详情',
            trigger: 'blur',
        },
    ],
    img: [
        {
            required: true,
            message: '请上传图片',
            trigger: 'change',
        },
    ],
    synopsis: [
        {
            required: true,
            message: '请选择分类',
            trigger: 'blur',
        },
    ],
});

function validateEmailDomain(rule, value, callback) {
    if (value === '') {
        callback(new Error('结束时间不能为空'));
    } else if (value < ruleForm.start_time) {
        callback(new Error('结束时间不能小于开始时间'));
    } else {
        callback();
    }
}

// 点击确认或编辑
const submitForm = (formEl) => {
    console.log(ruleForm);
    if (!formEl) return;
    
    // 提交前再次检查名称是否重复
    checkNameDuplicate().then(() => {
        if (nameDuplicateError.value) {
            ElMessage.warning('请修改重复的名称后再提交');
            return;
        }
        
        formEl.validate((valid) => {
            if (valid) {
                if (statused.value == '1') {
                    console.log(ruleForm);
                    lark_add({ token: tokens.token, uid: tokens.userinfo.id }, {
                        userid: tokens.userinfo.id,
                        group_id: ruleForm.synopsis,
                        title: ruleForm.name,
                        img: ruleForm.img,
                        sort: 0
                    }).then((res) => {
                        if (res.code == '1') {
                            ElMessage({
                                message: '新增成功',
                                type: 'success',
                            });
                            setTimeout(() => {
                                activeStatud.value = false;
                                activeStatu.value = true;
                            }, 1200);
                            render();
                        }
                    });
                } else if (statused.value == '2') {
                    lark_add({ token: tokens.token, uid: tokens.userinfo.id }, {
                        userid: tokens.userinfo.id,
                        id: ids.value,
                        group_id: ruleForm.synopsis,
                        title: ruleForm.name,
                        img: ruleForm.img,
                        sort: 0
                    }).then((res) => {
                        if (res.code == '1') {
                            ElMessage({
                                message: '编辑成功',
                                type: 'success',
                            });
                            setTimeout(() => {
                                activeStatud.value = false;
                                activeStatu.value = true;
                                fileListt.value = []
                            }, 1200);
                            render();
                        } else {
                            ElMessage({
                                message: '编辑失败，不能和原数据一致',
                                type: 'warning',
                            });
                        }
                    });
                }
            } else {
                ElMessage({
                    message: '请填写完整表单',
                    type: 'error',
                });
            }
        });
    });
};

// 编辑使用id
const ids = ref('');
const disableds = ref(true);

// 关闭新增
const closes = (formEl) => {
    console.log(formEl);
    activeStatu.value = true
    activeStatud.value = false
    formEl.resetFields();
    formEl.clearValidate()
    dialogTableVisible.value = false;
    files.value = false;
    ruleForm.name = ''
    fileListt.value = []
    nameDuplicateError.value = false
};

// 点击编辑
function edit(item) {
    fileListt.value = [{
        name: 'plant-1.png',
        url: testName + item.img,
    }]
    addText.value = '编辑'
    ids.value = item.id;
    ruleForm.name = item.title
    ruleForm.synopsis = item.group_id
    ruleForm.img = item.img
    activeStatud.value = true
    activeStatu.value = false
    disableds.value = false;
    statused.value = '2';
    originalName.value = item.title; // 保存原始名称用于查重比较
}

// 点击上传出现弹窗
function deletes(item) {
    console.log(item);
    centerDialogVisible.value = true;
    deleteids.value = item.id;
}
const deleteids = ref('');
const centerDialogVisible = ref(false);

// 确认删除
function deleteid() {
    lark_del(
        {
            token: tokens.token,
            uid: tokens.userinfo.id,
        },
        {
            userid: tokens.userinfo.id,
            ids: deleteids.value,
        }
    ).then((res) => {
        if (res.code == '1') {
            centerDialogVisible.value = false;
            ElMessage({
                message: '删除成功',
                type: 'success',
            });
            render();
        }
    });
}

// 分类名称搜索
function filters() {
    currentPage.value = 1
    console.log(inputed.value);
    let a = [];
    activeList.value = copyList.value.filter(function (item) {
        // 判断是否满足搜索条件
        if (String(item.title).indexOf(String(inputed.value)) > -1) {
            return a;
        }
    });
    currentPage.value = 1
}

// 分类日期搜索
const data_filters = () => {
    let end_time
    let start_time
    let ars = []
    if (time.value) {
        end_time = Date.parse(new Date(time.value[0]))
        start_time = Date.parse(new Date(time.value[1]))
    }
    activeList.value = copyList.value.filter((item) => {
        if (item.title ?
            item.title.indexOf(inputed.value) > -1 &&
            (time.value ?
                Date.parse(new Date(`${item.createtime}`)) > end_time &&
                Date.parse(new Date(` ${item.createtime}`)) < start_time : true
            ) : true
        ) {
            return item
        }
        ars.push(item)
    });
}

const shows = ref(false);

// 全选单选
const SelectArr = ref([])
const All_Delete = ref([])
const handleSelectionChange = (val) => {
    All_Delete.value = []
    SelectArr.value = val
    SelectArr.value.forEach(item => {
        console.log(item);
        All_Delete.value.push(item.id)
    })
    console.log(All_Delete.value);
}

// 批量删除
const centerDialogVisiblet = ref(false)
const st = ref([])
function deleList() {
    st.value = []
    console.log(All_Delete.value);
    st.value.push(All_Delete.value)
    if (All_Delete.value == '') {
        ElMessage({
            message: '请勾选要删除的门店类型',
            type: 'warning',
        })
    } else {
        centerDialogVisiblet.value = true
    }
}

// 确认批量删除
const deleteid_t = () => {
    lark_del({
        token: tokens.token,
        uid: tokens.userinfo.id
    }, {
        userid: tokens.userinfo.id,
        ids: st.value.join(','),
    }).then(res => {
        console.log(res, '删除成功或失败回调');
        centerDialogVisiblet.value = false;
        render();
        ElMessage({
            message: '删除成功',
            type: 'success',
        })
    })
}
</script>

<style>
/* 你的样式 */
.text {
    font-size: 14px;
}

.item {
    margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
    display: table;
    content: '';
}

.clearfix:after {
    clear: both;
}

.box-card {
    display: flex;
    height: 300px;
    width: 90%;
}

.handle {
    display: flex;
    align-items: center;
    justify-content: center;
}

.paging {
    display: flex;
    justify-content: center;
    margin-top: 10px;
    height: 70px;
}

.flex {
    display: flex;
    align-items: center;
    padding-bottom: 10px;
}

.flexBox {
    display: flex;
    width: 100%;
    align-items: center;
}
.el-upload-list--picture-card {
	--el-upload-list-picture-card-size: 100px;
	display: inline-flex;
	flex-wrap: wrap;
	margin: 0;
}

.el-upload--picture-card {
	--el-upload-picture-card-size: 99px;
	align-items: center;
	background-color: var(--el-fill-color-lighter);
	border: 1px dashed var(--el-border-color-darker);
	border-radius: 6px;
	box-sizing: border-box;
	cursor: pointer;
	display: inline-flex;
	height: var(--el-upload-picture-card-size);
	justify-content: center;
	vertical-align: top;
	width: var(--el-upload-picture-card-size);
}
.el-date-range-picker__content {
    box-sizing: border-box;
    float: left;
    margin: 0;
    padding: 16px;
    width: 38%;
}
</style>